package com.org.gundutubruk;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class GameSetting extends Activity{
	
	public static final String TAG = GameSetting.class.getSimpleName();
	
	int gbrApatar = R.drawable.apatar0;
	int gbrApatarKosong = R.drawable.apatar;
	
	int currMap;
	int currPlayer;
	boolean[] daptarcek;
	
	int jumPlayer;
	int jumGundu;
	
	int jumCek=0;
	Button incGundu;
	Button decGundu;
	TextView jumgundu;
	TextView namaPlayer;
	ImageView apatar;
	ImageView apatarcek;
	Button kiriPlayer;
	Button kananPlayer;
	Button lanjut;
	Button addPlayer;
	Button removePlayer;
	Button kiriMap;
	Button kananMap;
	Button panahbawah;
	Button panahatas;
	ImageView mapnow;
	Button tutor;
	RelativeLayout scrolling;
	boolean atas;
	float awal;
	float first;
	float curry;
	Thread tAtas;
	Thread tBawah;
	Thread blink;
	Context context;
	boolean isRunning;
	int Max;
	int stateBlink;
	static boolean isFirstTime=true;
	@Override
	public void onCreate(Bundle savedInstanceState) {
			
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.game_setting_layout);
		context=this;
		castItem();
		init();
		isiFungsiItem();
	}
	
	@Override
	public void onBackPressed(){
		nextAct3();
	}

	private void init(){				
		GameSettingHolder.statusTutorial=false;
		if(isFirstTime){
			showTutorial();
			isFirstTime=false;
		}
		//jika ada file serialisasi sebelomnya, playerholder yang dipake adalah yang serialisasi
		//jika tidak ada, instansiasi baru playerholder kosong(sudah otomatis ketika game dimulai)
		if(Utility.checkPlayerHolderAlreadyExist(this)) {
			Log.d(TAG,"ada file serialisasi");
			Utility.deserializePlayerHolder(this);
		}
		if(GameSettingHolder.modegame==3){
			Max=5;
			jumPlayer=2;
			jumGundu=1;
		}else if(GameSettingHolder.modegame==2){
			Max=10;
			jumPlayer=2;
			jumGundu=5;
		}else if(GameSettingHolder.modegame==1){
			Max=16;
			jumPlayer=2;
			jumGundu=5;
		}
		//membuat daftar cek false semua (belum ada yg dicek)
		daptarcek = new boolean[Utility.playerHolder.size()];
		
		GameSettingHolder.PlayingPlayer.clear();
		for(int i=0;i<daptarcek.length;i++){
			daptarcek[i]=false;
		}
		if(Utility.playerHolder.size()<=0){
			apatar.setImageResource(gbrApatarKosong);
			namaPlayer.setText("---");
			currPlayer=-1;
		}else{
			currPlayer=0;
			displayCurrPlayer();
		}
		currMap=1;
		mapnow.setImageResource(R.drawable.map1mini);
		jumgundu.setText(""+jumGundu);
		jumPlayer=0;
		atas=true;
		isRunning=true;
		stateBlink=1;
		final Handler h = new Handler();
		blink=new Thread(){
			public void run(){
				while(isRunning){
					h.post(new Runnable(){
						public void run(){
							if(stateBlink==1){
								panahatas.setBackgroundResource(R.drawable.atas2);
								panahbawah.setBackgroundResource(R.drawable.bawah2);
								stateBlink=0;
							}else{
								panahatas.setBackgroundResource(R.drawable.atas);
								panahbawah.setBackgroundResource(R.drawable.bawah);
								stateBlink=1;
							}
						}
					});
					try {
						sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		blink.start();
	}
	
	private void displayCurrPlayer(){
		Player p = Utility.playerHolder.get(currPlayer);
		apatar.setImageResource(gbrApatar+p.avatar);
		if(daptarcek[currPlayer])
			apatarcek.setImageResource(R.drawable.apatarcheck);
		else
			apatarcek.setImageResource(R.drawable.apataremboss);
		namaPlayer.setText(p.name);
	}
	
	private void castItem() {
		incGundu=(Button)findViewById(R.id.incrementjumgundu);
		decGundu=(Button)findViewById(R.id.decrementjumgundu);
		jumgundu=(TextView)findViewById(R.id.displayjumgundu);
		namaPlayer=(TextView)findViewById(R.id.namaplayernow);
		apatar=(ImageView)findViewById(R.id.displayapatar);
		apatarcek=(ImageView)findViewById(R.id.displayapatarcek);
		kiriPlayer=(Button)findViewById(R.id.decrementavatar);
		kananPlayer=(Button)findViewById(R.id.incrementavatar);
		lanjut=(Button)findViewById(R.id.next);
		addPlayer=(Button)findViewById(R.id.tambah);
		removePlayer=(Button)findViewById(R.id.kurang);
		scrolling=(RelativeLayout)findViewById(R.id.layoutdiscroll);
		kananMap=(Button)findViewById(R.id.incrementmap);
		kiriMap=(Button)findViewById(R.id.decrementmap);
		mapnow=(ImageView)findViewById(R.id.displaymap);
		panahatas=(Button)findViewById(R.id.panahatas);
		panahbawah=(Button)findViewById(R.id.panahbawah);
		tutor=(Button)findViewById(R.id.tutorial);
	}
	
	public boolean onTouchEvent(MotionEvent event){
		final int actioncode = event.getAction() & MotionEvent.ACTION_MASK;
		
			if(actioncode==MotionEvent.ACTION_DOWN){
				awal=event.getY();
				first=event.getY();
			}else if(actioncode==MotionEvent.ACTION_MOVE){
				curry=event.getY();
				scrolling.scrollBy(0, (int)(awal-curry));
				awal=curry;
			}else if(actioncode==MotionEvent.ACTION_UP){
				curry=event.getY();
				if(atas){
					if(first-curry<0||first-curry<100){
						scrolling.scrollTo(0, 0);
					}else if(first-curry>100){
						scrolling.scrollTo(0, 480);
						atas=false;
					}
				}else{
					if(first-curry>0||first-curry>-100){
						scrolling.scrollTo(0, 480);
					}else if(first-curry<-100){
						scrolling.scrollTo(0, 0);
						atas=true;
					}
				}
			}
		return false;
	}
	
	private void isiFungsiItem(){
		addPlayer.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				nextAct1();
			}
		});
		removePlayer.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				nextAct4();
			}
		});
		lanjut.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(jumPlayer>1){
					nextAct2();
				}else{
					Toast t = Toast.makeText(context, "Jumlah minimal player 2", Toast.LENGTH_SHORT);
					t.show();
				}
			}
		});
		tutor.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(GameSettingHolder.statusTutorial){
					GameSettingHolder.statusTutorial=false;
					tutor.setBackgroundResource(R.drawable.tutorial);
				}else{
					GameSettingHolder.statusTutorial=true;
					tutor.setBackgroundResource(R.drawable.tutorial_selected);
				}
			}
		});
		incGundu.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				int temp=jumGundu+1;
				Toast t;
				if(GameSettingHolder.modegame!=3){
					if(temp*jumPlayer<=Max){
						if(GameSettingHolder.PlayingPlayer.size()>0){
							int min=minJumGundu();
							if(temp<min)
								jumGundu++;
							else{
								t = Toast.makeText(context,"Ada pemain yang jumlah gundunya tidak mencukupi", Toast.LENGTH_SHORT);
								t.show();
							}
								
						}else
							jumGundu++;
					}else{
						t = Toast.makeText(context, "Jumlah gundu yang ditaruhkan telah mencapai maksimal", Toast.LENGTH_SHORT);
						t.show();
					}
				}else{
					t = Toast.makeText(context, "Pada duel, hanya dapat mempertaruhkan sebuah gundu", Toast.LENGTH_SHORT);
					t.show();
				}
				jumgundu.setText(""+jumGundu);
				Log.d("sds", "Jumlah gundu mode "+jumGundu);
			}
		});
		decGundu.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				int temp=jumGundu-1;
				Toast t;
				if(GameSettingHolder.modegame!=3){
					if(temp*jumPlayer<=Max&&temp>0){
						jumGundu--;
					}else if(temp*jumPlayer>Max){
						t = Toast.makeText(context, "Jumlah gundu yang ditaruhkan telah mencapai maksimal", Toast.LENGTH_SHORT);
						t.show();
					}else if(temp<=0){
						t = Toast.makeText(context, "Jumlah gundu yang ditaruhkan minimal 1", Toast.LENGTH_SHORT);
						t.show();
					}
				}else{
					t = Toast.makeText(context, "Pada duel, hanya dapat mempertaruhkan sebuah gundu", Toast.LENGTH_SHORT);
					t.show();
				}
				jumgundu.setText(""+jumGundu);
				Log.d("sds", "Jumlah gundu mode "+jumGundu);
			}
		});
		kiriPlayer.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Toast t=null;
				if(Utility.playerHolder.size()>0&&currPlayer>0){
					currPlayer--;
					displayCurrPlayer();
				}else if(Utility.playerHolder.size()==0){
					t=Toast.makeText(context, "Belum ada pemain yang dibuat", Toast.LENGTH_SHORT);
					t.show();
				}
				Log.d("sds", "Jumlah gundu mode "+jumGundu);
			}
		});
		kananPlayer.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Toast t=null;
				if(Utility.playerHolder.size()>0&&currPlayer<Utility.playerHolder.size()-1){
					currPlayer++;
					displayCurrPlayer();
				}else if(Utility.playerHolder.size()==0){
					t=Toast.makeText(context, "Belum ada pemain yang dibuat", Toast.LENGTH_SHORT);
					t.show();
				}
				Log.d("sds", "Jumlah gundu mode "+jumGundu);
			}
		});
		apatarcek.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Toast toast;
				if(currPlayer>-1){
					if(daptarcek[currPlayer]){
						daptarcek[currPlayer]=false;
						apatarcek.setImageResource(R.drawable.apataremboss);
						Player P = Utility.playerHolder.get(currPlayer);
						GameSettingHolder.PlayingPlayer.remove(P);
						jumPlayer--;
						jumCek--;
						toast=Toast.makeText(getApplicationContext(),"Pemain "+namaPlayer.getText()+" tidak ditambahkan", Toast.LENGTH_SHORT);
						toast.show();
					}else{
						if(Utility.playerHolder.size()>0){
							Player P = Utility.playerHolder.get(currPlayer);
							if(P.jumlahGundu>=jumGundu&&cekJumPlayer(jumPlayer)){
								jumPlayer++;
								GameSettingHolder.PlayingPlayer.add(P);
								daptarcek[currPlayer]=true;
								apatarcek.setImageResource(R.drawable.apatarcheck);
								jumCek++;
								toast=Toast.makeText(context, "Pemain "+namaPlayer.getText()+" ditambahkan, jumlah pemain ada "+jumPlayer, Toast.LENGTH_SHORT);
								toast.show();
							}else if(P.jumlahGundu<jumGundu){
								toast=Toast.makeText(context, "Jumlah gundu "+P.name+" kurang dari jumlah taruhan", Toast.LENGTH_SHORT);
								toast.show();
							}
						}else{
							toast=Toast.makeText(context, "Belum ada pemain yang dibuat", Toast.LENGTH_SHORT);
							toast.show();
						}
					}
				}else{
					toast=Toast.makeText(getApplicationContext(),"Belum ada pemain yang dibuat", Toast.LENGTH_SHORT);
					toast.show();
				}
			}
		});
		kiriMap.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(currMap>1){
					currMap--;
					mapnow.setImageResource(R.drawable.map1mini);
				}
			}
		});
		kananMap.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(currMap<2){
					currMap++;
					mapnow.setImageResource(R.drawable.map2mini);
				}
			}
		});
		panahatas.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Log.d("","Ini klik "+scrolling.getScrollY());
				final Handler h = new Handler();
				tAtas = new Thread(){
					public void run(){
		                int y = scrolling.getScrollY();
		                while(y>0){
		                    final int Y = y;
		                    h.post(new Runnable() {
		                        public void run() {
		                            scrolling.scrollTo(0, Y);
		                        }
		                    });
		                    y-=2;
		                    panahbawah.setClickable(false);
		                    try {
		                        sleep(100/12);
		                    } catch (InterruptedException e) {
		                    }
		                }
		                panahbawah.setClickable(true);
		            }
				};
				tAtas.start();
			}
		});
		panahbawah.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Log.d("","Ini klik "+scrolling.getScrollY());
				final Handler h = new Handler();
				tBawah = new Thread(){
					public void run(){
		                int y = scrolling.getScrollY();
		                while(y<480){
		                    final int Y = y;
		                    h.post(new Runnable() {
		                        public void run() {
		                            scrolling.scrollTo(0, Y);
		                        }
		                    });
		                    y+=2;
		                    panahatas.setClickable(false);
		                    try {
		                        sleep(100/12);
		                    } catch (InterruptedException e) {
		                    }
		                }
		                panahatas.setClickable(true);
		            }
				};
				tBawah.start();
			}
		});
	}
	
	protected boolean cekJumPlayer(int jumPlayer2) {
		int temp=jumPlayer+1;
		Toast t;
		if(temp*jumGundu<=Max){
			return true;
		}else if(temp*jumGundu>Max){
			t = Toast.makeText(context, "Jumlah gundu yang ditaruhkan telah mencapai maksimal "+Max, Toast.LENGTH_SHORT);
			t.show();
		}
		return false;
	}

	private void nextAct1(){
		this.startActivity(new Intent("android.intent.action.NEWPLAYER"));
		overridePendingTransition(R.anim.fade, R.anim.hold);
		isRunning=false;
		this.finish();
	}
	
	private void nextAct2(){		
		GameSound.changeMusicFromMainToGame(this);//ganti musik main menu jadi musik game
		GameSettingHolder.numPlayer=jumPlayer;
		GameSettingHolder.taruhan=jumGundu;
		GameSettingHolder.playMap=currMap;
		this.startActivity(new Intent("android.intent.action.GAMEPLAY"));
		overridePendingTransition(R.anim.fade, R.anim.hold);
		isRunning=false;
		this.finish();
	}
	
	private void nextAct3() {
		this.startActivity(new Intent("android.intent.action.GAMEMODE"));
		overridePendingTransition(R.anim.fade, R.anim.hold);
		isRunning=false;
		this.finish();		
	}
	private void nextAct4() {
		this.startActivity(new Intent("android.intent.action.REMOVEPLAYER"));
		overridePendingTransition(R.anim.fade, R.anim.hold);
		isRunning=false;
		this.finish();		
	}
	private void showTutorial(){
		AlertDialog.Builder builder5 = new AlertDialog.Builder(context);
		builder5.setTitle("Panduan 6/6")
		       .setMessage(R.string.lanjut)
		       .setCancelable(false)
		       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		final AlertDialog alert5 = builder5.create();
		
		AlertDialog.Builder builder4 = new AlertDialog.Builder(context);
		builder4.setTitle("Panduan 5/6")
		       .setMessage(R.string.tutorial)
		       .setCancelable(false)
		       .setPositiveButton("Lanjut", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                alert5.show();
		           }
		       })
		       .setNegativeButton("Tutup", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		final AlertDialog alert4 = builder4.create();
		
		AlertDialog.Builder builder3 = new AlertDialog.Builder(context);
		builder3.setTitle("Panduan 4/6")
		       .setMessage(R.string.scroll_help)
		       .setCancelable(false)
		       .setPositiveButton("Lanjut", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                alert4.show();
		           }
		       })
		       .setNegativeButton("Tutup", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		final AlertDialog alert3 = builder3.create();
		
		AlertDialog.Builder builder2 = new AlertDialog.Builder(context);
		builder2.setTitle("Panduan 3/6")
		       .setMessage(R.string.manage_pemain)
		       .setCancelable(false)
		       .setPositiveButton("Lanjut", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                alert3.show();
		           }
		       })
		       .setNegativeButton("Tutup", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		final AlertDialog alert2 = builder2.create();
		
		AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
		builder1.setTitle("Panduan 2/6")
		       .setMessage(R.string.karakter_pemain)
		       .setCancelable(false)
		       .setPositiveButton("Lanjut", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                alert2.show();
		           }
		       })
		       .setNegativeButton("Tutup", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		final AlertDialog alert1 = builder1.create();
		
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("Panduan 1/6")
			   .setMessage(R.string.gundu_taruhan)
		       .setCancelable(false)
		       .setPositiveButton("Lanjut", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                alert1.show();
		           }
		       })
		       .setNegativeButton("Tutup", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		AlertDialog alert = builder.create();
		alert.show();
	}
	private int minJumGundu(){
		int min;
		if(GameSettingHolder.PlayingPlayer.size()>0){
			min=GameSettingHolder.PlayingPlayer.get(0).jumlahGundu;
			for(Player P:GameSettingHolder.PlayingPlayer){
				if(P.jumlahGundu<min)
					min=P.jumlahGundu;
			}
			return min;
		}else{
			return -1;
		}
		
	}
}
